package com.bosssoft.boss_exam_web.Controller;


import com.bosssoft.boss_exam_core.enums.ResultCode;
import com.bosssoft.boss_exam_core.exception.*;
import com.bosssoft.boss_exam_core.util.web.ResponseUtil;
import com.bosssoft.boss_exam_core.validator.Order;
import com.bosssoft.boss_exam_core.validator.Sort;
import com.bosssoft.boss_exam_db.entity.Company;
import com.bosssoft.boss_exam_db.entity.Job;
import com.bosssoft.boss_exam_db.service.busines.AdminService;
import com.bosssoft.boss_exam_db.service.busines.JobService;
import com.bosssoft.boss_exam_db.service.busines.SubjectService;
import com.bosssoft.boss_exam_web.common.annotation.LoginAdmin;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/job")
@Validated
@Slf4j
@Api(value="岗位控制器")
public class JobController {

    //注入岗位服务
    @Autowired
    private JobService jobService;

    //注入管理员服务
    @Autowired
    private AdminService adminService;

    //注入科目服务
    @Autowired
    private SubjectService subjectService;

    @ApiOperation(value="岗位查询", notes="可根据岗位名称查询岗位" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="name", value="岗位名称", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="page", value="当前页码", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="limit", value="每页显示条数", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="sort", value="排序依据", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="order", value="排序方式", dataType = "String", required=false, dataTypeClass=String.class)
    })
    @GetMapping("/list")
    public Object list(@LoginAdmin String adminId,
                       @RequestParam String name,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        if ( adminId == null) {
            return ResponseUtil.unlogin();
        }
        //查询当前用户所在公司
        Company company=adminService.selectAdminBelongCompany(adminId);
        if(company==null){
            log.error("【严重警告】该管理员没有公司");
            throw new BusinessException("该管理员，没有归属公司");
        }
        PageInfo<Job> jobPageInfo = jobService.queryByCondition(company,name,page, limit, sort, order);
        if(jobPageInfo==null){
            log.error("【业余错误】，查询pageInfo为空");
            throw new QueryDataException();
        }else {
            Map<String, Object> data = new HashMap<>();
            data.put("total", jobPageInfo.getTotal());
            data.put("items", jobPageInfo.getList());
            return ResponseUtil.ok(data);
        }
    }

    @ApiOperation(value="岗位添加", notes="添加岗位" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="job", value="岗位对象json", dataType = "Job", required=true, dataTypeClass= Job.class),
    })
    @PostMapping("/create")
    public Object create(@LoginAdmin String adminId, @RequestBody Job job) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        //查询当前用户所在公司
        Company company=adminService.selectAdminBelongCompany(adminId);
        if(company==null){
            log.error("【严重警告】该管理员没有公司");
            throw new BusinessException("该管理员，没有归属公司");
        }
        job.setCompanyId(company.getId());
        int recordNum = jobService.saveNotNull(job);
        if(recordNum==1){
            return ResponseUtil.ok(job);
        }else{
            log.error("【系统错误】 保存岗位失败");
            throw  new UpdateEntityException();
        }
    }

    @ApiOperation(value="岗位详细信息查询", notes="可根据岗位的ID查询详情" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="岗位ID，非空", dataType = "String", required=true, dataTypeClass=String.class),
    })

    @PostMapping("/read")
    public Object read(@LoginAdmin String  adminId,@RequestParam String id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Job job = null;
        try {
            job = jobService.selectByKey(id);
        }  catch (NoSuchMethodException | InvocationTargetException |IllegalAccessException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }catch (Exception e){
            System.err.println(e);
            log.error("【业务错误】 读取实体异常"+e);
            throw  new QueryDataException();
        }
        return ResponseUtil.ok(job);
    }


    @ApiOperation(value="岗位更新", notes="更新岗位" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="job", value="岗位对象json，必须携带岗位ID", dataType = "Job", required=true, dataTypeClass= Job.class),
    })
    @PostMapping("/update")
    public Object update(@LoginAdmin String  adminId, @RequestBody Job job) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        int recordNum = jobService.updateNotNull(job);
        if(recordNum==1){
            return ResponseUtil.ok(job);
        }else{
            log.error("【系统错误】 保存岗位失败");
            throw  new UpdateEntityException();
        }
    }

    @ApiOperation(value="岗位删除", notes="可根据岗位的ID逻辑删除岗位" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="岗位ID，非空", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @PostMapping("/delete")
    public Object delete(@LoginAdmin String adminId, @RequestParam String id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Job job = new Job();
        job.setId(id);
        try {
            int i = jobService.deleteForLogic(job);
        } catch (NoSuchMethodException|IllegalAccessException|InvocationTargetException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }catch (Exception e) {
            log.info("【业务错误】 逻辑删除岗位异常"+e);
            throw  new DeleteEntityException();
        }
        return ResponseUtil.ok();
    }

    @ApiOperation(value="查询岗位", notes="查询当前用户所在公司开设的所有岗位" ,httpMethod="GET",response = Object.class)
    @GetMapping("/jobs")
    public Object getJobByCompany(@LoginAdmin String adminId){
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Company company=adminService.selectAdminBelongCompany(adminId);
        if(company==null){
            log.error("【严重警告】该管理员没有公司");
            throw new BusinessException("该管理员，没有归属公司");
        }
        List<Job> jobs= jobService.queryByCompany(company.getId());
        return ResponseUtil.ok(jobs);
    }

}
